package interceptors

import (
	"context"
	"encoding/json"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
	"maintenance/pkg/consts"
)

func Token2UidInterceptor() grpc.UnaryClientInterceptor {
	return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
		var uid string
		ctxUid := ctx.Value(consts.UserIDKey)
		if ctxUid != nil {
			uid = ctxUid.(json.Number).String()
		}

		md := metadata.New(map[string]string{
			consts.UserIDKey: uid,
		})
		ctx = metadata.NewOutgoingContext(ctx, md)
		return invoker(ctx, method, req, reply, cc, opts...)

	}
}
